const error_unknow = -1
const error_unknow_url = -2


import { 
    decodeAddress, 
    signatureVerify
  } from '@polkadot/util-crypto';
import { u8aToHex } from '@polkadot/util';
import { ApiPromise, WsProvider } from '@polkadot/api';

var api = null
var wsProvider = new WsProvider('wss://dotdev.eieichina.com/wss'); // 这个是rpc地址，需要根据实际修改
ApiPromise.create({ provider: wsProvider }).then((api_tmp) => {
    api = api_tmp
})
function verify(msg){
    const msg_addr = msg.address
    const msg_timestamp = parseInt(msg.timestamp)
    const msg_sign = msg.sign;
    const publicKey = decodeAddress(msg_addr);
    const hexPublicKey = u8aToHex(publicKey);
    return signatureVerify(JSON.stringify({address:msg_addr, timestamp:msg_timestamp}), msg_sign, hexPublicKey).isValid
}

function handle_post(url, param, cb){
    console.log("handle:", url, "param:", param)
    var rtn = {result: -1, msg:"error_unknow"}
    switch(url){
        case "/login": {
            rtn = {
                result: 0,
                msg: "ok"
            }
            // 验证签名
            rtn.result = verify(param) && (Math.abs(param.timestamp - Date.parse(new Date())) < 5000)
            rtn.msg = rtn.result ? "ok":"verify error or timeout!"
            cb(rtn)
            break;
        }
        case "/get_member_nft_count": {
            rtn = {
                result: 0,
                msg: ""
            }
              api.query.nft.balanceCount(param.address, 1, (balance) => {
                console.log(`The nft balances are`, balance.toString());
                rtn.msg = balance.toString()
                cb(rtn)
              }).catch(function(e){
                console.log(e, "=========================")
                rtn.result = -2;
                cb(rtn)
              })
            
            break
            
        }
        default: {
            rtn.result = -2;
            rtn.msg = "url{" + url + "} unknow";
            cb(rtn)
            break;
        }
    }
    
}
function handle_get(url, param){
    return "1122";
}


export {handle_post, handle_get};